package com.sztle.admodule.outstatus;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.hardware.display.DisplayManager;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;

import com.sztle.admodule.GmAdManager;
import com.sztle.admodule.IAdListener;
import com.sztle.admodule.IAdSparkResult;
import com.sztle.admodule.IEnterHomeCallback;
import com.sztle.admodule.IPolicyDialogCallback;
import com.sztle.admodule.IShowListener;
import com.sztle.admodule.handler.FullIntlHandler;
import com.sztle.admodule.apiprocessor.OutCommProcessor;
import com.sztle.admodule.apiprocessor.OutIntAdApi;
import com.sztle.admodule.apiprocessor.OutRewardAdApi;
import com.sztle.admodule.apiprocessor.OutSplashAdApi;
import com.sztle.admodule.apiprocessor.listener.IOutRewardCallback;
import com.sztle.admodule.apiprocessor.listener.IStartProgress;
import com.sztle.admodule.someutils.SPUtils;
import com.sztle.admodule.someutils.ThreadUtils;
import com.sztle.admodule.control.AppInfoManager;
import com.sztle.admodule.control.event.SzTrackEvents;
import com.sztle.admodule.control.manager.ControlManager;
import com.sztle.admodule.control.manager.UMengManager;
import com.sztle.admodule.control.utils.UserDeviceUtils;
import com.sztle.admodule.myutils.PolicyDialogHelper;

public class AppStatusProcessor {

    private static AppParam appParam;
    private static Application sApp;
    private static boolean privacyScroll = false;
    private static boolean privacyScrollBottom = false;

    private static boolean isFromInit = true;
    private static String keyPrivacyScroll = "keyPrivacyScroll";
    private static String keyPrivacyBottom = "keyPrivacyBottom";

    private static boolean background = true;
    private static Activity topActivity;

    public static boolean isBackground() {
        return background;
    }

    public static boolean canPopTimerAd() {
        if (isBackground()) {
            return false;
        }
        if (topActivity == null || topActivity.isDestroyed()) {
            return false;
        }
        return true;
    }

    public static void setBackground(boolean background) {
        AppStatusProcessor.background = background;
    }

    public static void setTopActivity(Activity topActivity) {
        AppStatusProcessor.topActivity = topActivity;
    }

    public static Activity getTopActivity() {
        return topActivity;
    }

    public static void setPrivacyScroll(boolean privacyScroll) {
        AppStatusProcessor.privacyScroll = privacyScroll;
        boolean oldValue = isPrivacyScroll();
        if (!oldValue && privacyScroll) {
            SPUtils.getInstance().put(keyPrivacyScroll, true);
            if (AppInfoManager.isHomeActivityExist()) {
                ControlManager.justQuerySingleRisk();
            }

        }
    }

    public static boolean isNeedAwakeSplash() {
        if (UserDeviceUtils.isGMore()) {
            return false;
        }
        return GmAdManager.isUseAdExp();
    }

    public static boolean isPrivacyScroll() {
        return SPUtils.getInstance().getBoolean(keyPrivacyScroll, false);
    }

    public static void setPrivacyScrollBottom(boolean privacyScrollBottom) {
        AppStatusProcessor.privacyScrollBottom = privacyScrollBottom;
        boolean oldValue = isPrivacyScrollBottom();
        if (!oldValue && privacyScrollBottom) {
            SPUtils.getInstance().put(keyPrivacyBottom, true);
            if (AppInfoManager.isHomeActivityExist()) {
                ControlManager.justQuerySingleRisk();
            }

        }
    }

    public static boolean isPrivacyScrollBottom() {
        return SPUtils.getInstance().getBoolean(keyPrivacyBottom, false);
    }

    public static boolean isDebug() {
        if (appParam == null) {
            return false;
        }
        return appParam.debug;
    }

    public static String getChannel() {
        String channel = "baidu";
        if (appParam != null) {
            channel = appParam.channel;
        }
        return channel;
    }


    public static Application getApp() {
        return sApp;
    }

    public static AppParam getAppParam() {
        return appParam;
    }

    public static void statusStartApp(Application application, AppParam params) {
        if (application == null) {
            return;
        }
        sApp = application;
        appParam = params;
        ControlManager.init(application);

        ControlManager.reportAppLog(ControlManager.isBluetoothEnabled() ? SzTrackEvents.user_bluetooth_open : SzTrackEvents.user_bluetooth_close);
        DisplayManager displayManager = (DisplayManager) application.getSystemService(Context.DISPLAY_SERVICE);
        displayManager.registerDisplayListener(new DisplayManager.DisplayListener() {
            @Override
            public void onDisplayAdded(int displayId) {
                ControlManager.reportAppLog(SzTrackEvents.user_start_record);
                GmAdManager.forceCloseAd();
                SPUtils.getInstance().put("isRecord", true);
            }

            @Override
            public void onDisplayRemoved(int displayId) {
                ControlManager.reportAppLog(SzTrackEvents.user_stop_record);
                SPUtils.getInstance().put("isRecord", true);
                GmAdManager.forceCloseAd();
            }

            @Override
            public void onDisplayChanged(int displayId) {

            }
        }, null);
        if (SPUtils.getInstance().getBoolean("isRecord", false)) {
            GmAdManager.forceCloseAd();
        }

    }

    public static boolean isGetAppServerConfig() {
        return ControlManager.isGetPreConfig();
    }

    //注意非隐私的情况进入该页面
    public static void statusEnterPrivacyWebPage(WebView webView) {
        AppStatusProcessor.setPrivacyScroll(true);
        webView.setOnScrollChangeListener(new View.OnScrollChangeListener() {
            @Override
            public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                int contentHeight = Math.round(webView.getContentHeight() * webView.getScale());
                int curViewHeight = webView.getHeight() + webView.getScrollY();
                if (contentHeight - curViewHeight < 50) {
                    AppStatusProcessor.setPrivacyScrollBottom(true);
                }
            }
        });
    }

    public static void statusInitSdk(Activity activity) {
        if (activity == null
                || activity.isDestroyed()) {
            return;
        }
        UMengManager.init();
        ControlManager.startRiskTask();
        GmAdManager.initAdSpark(activity, getChannel(), new IAdSparkResult() {
            @Override
            public void onDidResult(String did) {
                SPUtils.getInstance().put("did", did);
            }

            @Override
            public void onOaidResult(String oaid) {
                if (!TextUtils.isEmpty(oaid)) {
                    ControlManager.setOaidAndStartRiskTask(oaid, ControlManager.OAID_FROM_ADSPARK);
                }
            }
        });
        OutIntAdApi.clearFlag();
        OutSplashAdApi.getInstance().resetAdFlag();
    }

    public static boolean isSplashEnd() {
        return OutSplashAdApi.getInstance().isLoadEnd();
    }

    public static void setSplashEnd() {
        OutSplashAdApi.getInstance().setLoadEnd();
    }

    public static void statusLoadingProgressCheck(Activity activity, ViewGroup adContainer, IStartProgress listener) {
        if (activity == null
                || activity.isDestroyed()) {
            return;
        }
        ControlManager.checkHitApp();
        GmAdManager.checkInit(new IAdListener() {
            @Override
            public void initComplete(boolean isHasInit, boolean result) {
                if (!isHasInit && result) {
                    ControlManager.reportAppLog(SzTrackEvents.gm_init_success);
                }
            }
        });
        OutSplashAdApi.getInstance().checkSplashAd(activity, adContainer, listener);
    }

    public static void statusHomeShowAd(Activity activity, IShowListener showListener) {
        if (activity == null || activity.isDestroyed()) {
            return;
        }
        if (ControlManager.getHomeIntsCount() == 0 && ControlManager.getHomeRewardCount() == 0) {
            if (showListener != null) {
                showListener.onFinalEnd(false);
                return;
            }
        }
        //这两个不可能都为0
        int intCount = ControlManager.getHomeIntsCount();
        if (intCount == 0) {
            OutRewardAdApi.showHomeRewardAd(activity, "home_page", new IOutRewardCallback() {
                @Override
                public void onRewardEnd() {
                    if (showListener != null) {
                        showListener.onFinalEnd(false);
                    }
                }
            });
        } else if (intCount == 1) {
            OutIntAdApi.showSingleIntAd(activity, "home_page", new IShowListener() {
                @Override
                public void onFinalEnd(boolean result) {
                    OutRewardAdApi.showHomeRewardAd(activity, "home_page", new IOutRewardCallback() {
                        @Override
                        public void onRewardEnd() {
                            if (showListener != null) {
                                showListener.onFinalEnd(result);
                            }
                        }
                    });
                }
            });
        } else {
            OutIntAdApi.showTwoIntAd(activity, "home_page", new IShowListener() {
                @Override
                public void onFinalEnd(boolean result) {
                    OutRewardAdApi.showHomeRewardAd(activity, "home_page", new IOutRewardCallback() {
                        @Override
                        public void onRewardEnd() {
                            if (showListener != null) {
                                showListener.onFinalEnd(result);
                            }
                        }
                    });
                }
            });
        }

    }

    private static boolean isShowPrivacy = false;

    public static void statusHomePrivacy(Activity activity, IPolicyDialogCallback dialogCallback) {
        if (activity == null || activity.isDestroyed()) {
            return;
        }
        if (!AppInfoManager.isUserAgree() && !isShowPrivacy) {
            isShowPrivacy = true;
            PolicyDialogHelper.showPolicyDialog(activity, new IPolicyDialogCallback() {
                @Override
                public void onSure() {
                    isShowPrivacy = false;
                    AppStatusProcessor.statusAgreePolicy();
                    OutIntAdApi.showSingleIntAd(activity, "home_agree");
                    if (dialogCallback != null) {
                        dialogCallback.onSure();
                    }
                }

                @Override
                public void onCancel() {
                    isShowPrivacy = false;
                    if (dialogCallback != null) {
                        dialogCallback.onCancel();
                    }
                }

                @Override
                public void onClickUserPolicy() {
                    if (dialogCallback != null) {
                        dialogCallback.onClickUserPolicy();
                    }
                }

                @Override
                public void onClickPrivacyPolicy() {
                    if (dialogCallback != null) {
                        dialogCallback.onClickPrivacyPolicy();
                    }
                }
            });
        } else if (dialogCallback != null) {
            dialogCallback.onSure();
        }
    }

    public static void statusEnterHome(Activity activity, IEnterHomeCallback enterHomeCallback) {
        isFromInit = true;
        AppInfoManager.setHomeActivityExist(true);
        ThreadUtils.runOnUiThreadDelayed(new Runnable() {
            @Override
            public void run() {
                ControlManager.cancelExecuteRiskOpen();
                if (OutCommProcessor.isFirstEnterApp()) {
                    OutCommProcessor.resetFirstEnterApp();
                    ControlManager.reportAppLog(SzTrackEvents.enter_home_page);
                }
            }
        }, 1000);

        statusHomeShowAd(activity, new IShowListener() {
            @Override
            public void onFinalEnd(boolean result) {
                AppStatusProcessor.statusHomePrivacy(activity, new IPolicyDialogCallback() {
                    @Override
                    public void onCancel() {
                        activity.finish();

                    }

                    @Override
                    public void onClickUserPolicy() {
                        if (enterHomeCallback != null) {
                            enterHomeCallback.onClickUserPolicy();
                        }
                    }

                    @Override
                    public void onClickPrivacyPolicy() {
                        if (enterHomeCallback != null) {
                            enterHomeCallback.onClickPrivacyPolicy();
                        }
                    }

                    @Override
                    public void onSure() {

                    }
                });
            }
        });


    }


    public static void statusStopHome() {
        FullIntlHandler.closeAd();
        isFromInit = false;
    }

    public static void statusOnIntentHome(Activity activity) {
        if (activity == null) {
            return;
        }
        if (!isFromInit) {
            OutIntAdApi.showTwoIntAd(activity, "home");
        }
    }

    public static void statusAgreePolicy() {
        AppInfoManager.userAgreePolicy();
        if (OutCommProcessor.isFirstEnterApp()) {
            ControlManager.reportAppLog(SzTrackEvents.agree_privacy);
        }
    }


//    public static void statusHomeBackKey(Activity activity) {
//        if (activity == null || activity.isDestroyed()) {
//            return;
//        }
//        OutIntAdApi.showSingleIntAd(activity, "home_back", new IShowListener() {
//            @Override
//            public void onFinalEnd(boolean result) {
//                activity.finish();
//            }
//        });
//
//    }

}
